<template>
    <div class="main">
        <div class="left">
            <el-page-header style="margin-bottom: 20px" @back="dialog = true">
                <template #content>
                    <span class="text"> HDC AI </span>
                </template>
            </el-page-header>
            <div class="history">
                <el-space direction="vertical">
                    <el-card @click="newSession" style="width: 250px; cursor: pointer;" shadow="never">
                        <div style="display: flex; align-items: center;">
                            <el-icon style="margin-right: 10px;">
                                <Plus />
                            </el-icon>
                            <span class="text">新建会话</span>
                        </div>
                    </el-card>
                    <el-card v-for="(msg, index) in msgHistory" :key="index" shadow="never"
                        style="width: 250px; cursor: pointer;" @click="getHistory(msg._id, index)">
                        <div style="display: flex; justify-content: space-between;">
                            <text class="time">{{ formatTimestamp(msg.time) }}</text>
                            <el-tag type="success" v-if="indexTag === index" size="small">会话中</el-tag>
                        </div>
                        <p class="text">{{ msg.list[0].content }}...</p>
                    </el-card>
                </el-space>
            </div>

        </div>
        <div class="right">

            <div v-show="msgStore.list.length === 0"
                style="display: flex; justify-content: center; align-items: center; flex: 1; width: 95%;">
                <img src="https://hdc-res-2023-1317708264.cos.ap-guangzhou.myqcloud.com/login_swiper%2Faislogo.png"
                    alt="AI" />
            </div>

            <div v-show="msgStore.list.length > 0" class="content" id='message-box'>
                <div v-for="(msg, index) in msgStore.list" :key="index">
                    <div class="user" v-if="msg.role === 'user'">
                        <el-avatar :size="30" :src="tabStore.avatar" />
                        <p class="username">{{ tabStore.username }}</p>
                    </div>
                    <div class="ai" v-if="msg.role === 'assistant'">
                        <el-button size="large" link>
                            <SvgIcon name="ai" width="2em" height="2em"></SvgIcon>
                        </el-button>
                        <p class="username">HDC AI</p>
                    </div>
                    <div class="text" v-highlight v-html='msg.content'></div>
                </div>
            </div>


            <div class="input">
                <el-input size="large" v-model="msgValue" type="text" placeholder="输入关键词..." />
                <div style="width: 20px;"></div>
                <el-button v-show="!msgStore.loading" :disabled="msgValue === ''" @click="submitMsg" size="large"
                    :icon="Position" type="primary" circle plain></el-button>
                <el-button v-show="msgStore.loading" size="large" :icon="Loading" type="success">AI生成中</el-button>
            </div>

        </div>
        <el-dialog v-model="dialog" width="500" center>
            <span>
                是否存储会话记录?
            </span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="goBack(false)">取消</el-button>
                    <el-button @click="goBack(true)">
                        保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
import { Position, Loading } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted, nextTick } from 'vue'
import { useTabStore } from '@/store/useTabStore';
import SvgIcon from '@/components/Icons/index.vue';
import TTSRecorder from './TTSRecorders.js'
import { userMsgStore } from '@/store/useAIStore'
import { postAiContent, getAiContent, putAiContent } from '@/server/home/http';
import { formatTimestamp } from '@/utils/time'

const dialog = ref(false)
const msgStore = userMsgStore()
const tabStore = useTabStore()
const route = useRoute()
const router = useRouter()
const msgValue = ref("")

const msgHistory = ref([])



let ttsRecorder = new TTSRecorder()
const msgDom = ref(null)

const indexTag = ref(-1)



onMounted(() => {
    getAiContent({ user_id: route.query.id }).then((res) => {
        if (res.code === 200) {
            msgHistory.value = res.data
            // console.log(msgHistory.value);

        }
    })

    msgDom.value = document.getElementById("message-box")
    // msgList.value = msgStore.list
    scroll()
})


const goBack = (status: boolean) => {
    if (status) {
        if (msgStore.list.length != 0 && msgStore.aiCol_id === "") {
            saveContent()
            router.push({ name: "Home" })
        } else {
            changeHistory()
            router.push({ name: "Home" })
        }
        msgStore.setAiCol_id("")
        msgStore.clear()
    }
}

// 滚动到最底部
const scroll = () => {
    nextTick(() => {
        msgDom.value.scrollTop = msgDom.value.scrollHeight
    })
}

// 发送消息
const submitMsg = async () => {
    msgStore.setLoading(true)
    msgStore.userAddMsg(msgValue.value)
    msgValue.value = ""
    // 开始提问
    ttsRecorder.start(msgStore, msgDom)
    scroll()
}


//保存数据
const saveContent = async () => {
    let data = {
        user_id: tabStore.userId,
        //时间戳
        time: new Date().getTime(),
        list: msgStore.list
    }
    await postAiContent(data)
}

//修改历史记录
const changeHistory = async () => {
    let data = {
        user_id: tabStore.userId,
        list: msgStore.list,
        time: new Date().getTime()
    }
    await putAiContent(msgStore.aiCol_id, data)
}



const getHistory = async (id: string, index: number) => {
    if (msgStore.aiCol_id === "" && msgStore.list.length != 0) {
        saveContent()
    }
    indexTag.value = index
    if (msgStore.aiCol_id === id) {
        return
    }
    //获取历史记录的时候判断是否有值
    if (msgStore.list.length != 0) {
        changeHistory()
    }
    msgStore.setAiCol_id(id)
    getAiContent({ _id: id }).then((res) => {
        if (res.code === 200) {
            msgStore.setList(res.data.list)
            scroll()
        }
    })
}


const newSession = () => {
    changeHistory()

    msgStore.setAiCol_id("")
    msgStore.clear()
    indexTag.value = -1
}



</script>

<style scoped lang="scss">
:deep(.el-card__body) {
    padding: 5px;
}

:deep(.el-input__wrapper) {
    border-radius: 20px;
}

/* 隐藏所有滚动条 */
::-webkit-scrollbar {
    display: none;
}


.main {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    display: flex;

    .left {
        width: 250px;
        padding: 10px;
        overflow-y: auto;
        border-right: 1px solid #f0f0f0;


        .time {
            font-size: 10px;
            font-weight: bold;
            letter-spacing: 1px;
            line-height: 2;
        }

        .text {
            font-size: 12px;
            font-weight: bold;
            letter-spacing: 1px;
            line-height: 2;
        }
    }

    .right {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;

        .content {
            padding: 10px;
            padding-bottom: 30px;
            width: 95%;
            flex: 1;
            overflow-y: auto;





            .text {
                font-size: 12px;
                font-weight: bold;
                letter-spacing: 1px;
                line-height: 2;
                text-align: left;
            }


            .user {
                display: flex;
                align-items: center;

                .username {
                    margin-left: 5px;
                }
            }


            .ai {
                display: flex;
                align-items: center;

                .username {
                    color: #1897da;
                    margin-left: 5px;
                }
            }




        }

        .input {
            width: 80%;
            height: 70px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

    }

}
</style>